package com.cabal.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.cabal.module.web.StreamFilter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource(name = "requestMessageLogInterceptor")
    private HandlerInterceptor requestMessageLogInterceptor;

    @Resource(name = "authorizationInterceptor")
    private HandlerInterceptor authorizationInterceptor;

    @Bean
    public HttpMessageConverters converters(){
        return new HttpMessageConverters(new FastJsonHttpMessageConverter());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] swaggerExcludes = new String[]{"/swagger-ui.html","/swagger-resources/**","/webjars/**","/websocket/**"};
        registry.addInterceptor(requestMessageLogInterceptor).addPathPatterns("/**").excludePathPatterns(swaggerExcludes);
        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**").excludePathPatterns(swaggerExcludes);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        // 解决 SWAGGER 404报错
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

    }

    @Bean
    public FilterRegistrationBean streamFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        StreamFilter streamFilter = new StreamFilter();
        filterRegistrationBean.setFilter(streamFilter);
        List<String> urls = new ArrayList<>();
        urls.add("/*");
        // 对支付信息推送接口进行过滤
        urls.add("/api/sitd/payinfo");
        // 对报关单推送接口进行过滤
        urls.add("/api/sitd/reportOrder");
        filterRegistrationBean.setUrlPatterns(urls);
        return filterRegistrationBean;
    }

}